import { getMenus, getShops, queryTables } from "@src/api/catering";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import location from "@src/store/location";
import { getDistance } from "@src/common/utils";
import router from "@src/router";
import cart from "../../store/cart";
import { getCoupon, pullDownCoupon } from "@src/api/mall/store";
import base from "@src/store/base";
const Private_Domain_Meal_Method = "Private_Domain_Meal_Method";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [
    {
      store: cart,
      fields: ["cartList", "totalFee", "num", "hasDinnerType", "dinnerList"],
      actions: ["initCart", "setDinnerType", "setDinnerList"],
    },
    {
      store: location,
      fields: ["latitude", "longitude", "auth"],
      actions: ["getLocation", "showAuthTip"],
    },
    {
      store: base,
      fields: ["themeColor", "themeTitleColor", "isiPhoneX"],
    },
  ],
  data: {
    shopId: null,
    tableNo: null,
    specDialog: null,
    carList: [],
    nodesTop: [],
    currentIndex: 0,
    contentId: "",
    shopInfo: {
      isOpenTime: true,
    },
    showDetail: false,
    contentHeight: "",
    dinnerType: 0,
    showDinner: false,
    deskId: "",
    noChange: false,
    couponList: [],
    dinnerObj: "",
    commodityList: "",
  },
  observers: {
    shopId: function (shopId) {
      if (shopId) {
        // 初始化对应店铺的购物车
        this.initCart(shopId);
        getApp().globalData.dinnerShopid = shopId;
      }
    },
  },
  methods: {
    onShow() {
      // wx.removeStorageSync(Private_Domain_Meal_Method)
      // 接收从门店列表页（store-list）返回当前页的数据
      const pages = getCurrentPages();
      const currPage = pages[pages.length - 1];
      console.log(
        "点餐---接收门店列表的数据 currPage",
        currPage.data.storeData
      );
      if (currPage.data.storeData) {
        let shopId = currPage.data.storeData.shopId;
        this.setData({
          shopId,
        });
        this.fetchData();
      }
      this.setData({
        dinnerObj: "",
      });
    },
    onLoad(options) {
      console.log("点餐options---", options);
      wx.showShareMenu({
        withShareTicket: true,
        menus: ["shareAppMessage", "shareTimeline"],
      });
      this.getCoupon();

      var shopId = null;
      let tableNo = null;
      if (options.GLOBAL_SHOP_ID) {
        shopId = options.GLOBAL_SHOP_ID;
      }
      if (options.shopId) {
        shopId = options.shopId;
      }
      if (options.tableNo) {
        tableNo = decodeURIComponent(options.tableNo);
      }
      this.setData({
        shopId,
        tableNo,
      });
      // 通过桌码进来的
      if (options.deskId) {
        let { deskId, shopId } = options;
        getApp().globalData.dinnerShopid = shopId;
        this.setData({
          deskId,
          shopId,
        });
        // this.setData({ dinnerType: 0, showDinner: true })
      }
      // 如果存在这个字段则是跳转进来的 goodsSerial分类id
      //  wx.nextTick(() => {
      if (options.goodsSerial) {
        let { dinnerShopid } = getApp().globalData;
        if (dinnerShopid != options.storeId) {
          getApp().globalData.dinnerType = 0;
        }
        getApp().globalData.dinnerShopid = options.storeId;
        this.setData({
          shopId: options.storeId,
        });
        let classId = {
          currentTarget: {
            dataset: {
              id: options.goodsSerial,
            },
          },
        };
        this.handleCategory(classId);
      }
      // })

      // 通过分享进来的
      if (options.shopId && options.type == "share") {
        getApp().globalData.dinnerShopid = options.shopId;
        this.setData({
          shopId: options.shopId,
        });
      }
      let globalData = getApp().globalData;
      // 存在桌码
      if (getApp().globalData.dinnerTabNum) {
        this.setData({
          tableNo: getApp().globalData.dinnerTabNum,
          shopId: globalData.dinnerShopid,
        });
      }
      // // 设置过就餐方式
      // if(globalData.dinnerType !=0){
      //   this.setData({dinnerType:globalData.dinnerType,shopId:globalData.dinnerShopid})
      // }else{
      // // 没有设置过就餐方式
      //   this.setData({ dinnerType: 0, showDinner: true })
      // }

      this.setConetHeight();
    },
    onShareAppMessage(e) {
      let { shareText, img, shopId } = this.data.shopInfo;
      img
        ? img
        : (img =
            "https://hyyxboss.oss-cn-shenzhen.aliyuncs.com/business/1/shop_default_logo.png");
      return {
        title: shareText,
        imageUrl: getApp().toFullUrl(img),
        path: `pages/codeModul/pages/index/main?shopId=${shopId}&type=share`,
        success: (res) => {},
      };
    },
    handleSelectSpec(e) {
      this.selectComponent("#spec-dialog").open(
        e.detail.goods,
        this.data.shopInfo.shopId
      );
    },
    changeDetail() {
      this.setData({
        showDetail: !this.data.showDetail,
      });
      this.setConetHeight();
    },
    onReady() {},
    onLogin() {
      this.getLocation()
        .then((res) => {
          if (this.data.shopId) {
            this.fetchData();
          } else {
            this.getNearbyShop(res.latitude, res.longitude);
          }
        })
        .catch((error) => {
          this.showAuthTip(error);
          if (this.data.shopId) {
            this.fetchData();
          } else {
            this.getNearbyShop();
          }
        });
    },
    getNearbyShop(latitude, longitude) {
      let data = {};
      if (latitude) {
        data = {
          latitude,
          longitude,
        };
      }
      getShops(data).then((res) => {
        let shopId = null;
        if (res.data.length > 0) {
          for (let i = 0; i < res.data.length; i++) {
            if (shopId) {
              break;
            } else {
              if (res.data[i].isOpenTime) {
                shopId = res.data[i].shopId;
                this.setData({
                  shopId: res.data[i].shopId,
                });
                getApp().globalData.dinnerShopid = res.data[0].shopId;
              }
            }
          }
          if (res.data.length == 1) {
            this.setData({
              shopId: res.data[0].shopId,
            });
            this.setData({
              noChange: true,
            });
            getApp().globalData.dinnerShopid = res.data[0].shopId;
          }
          this.fetchData();
        } else {
          // 异常处理
          wx.showToast({
            title: "尚未配置店铺",
            icon: "none",
            duration: 5000,
          });
        }
        this.setGlobalTabNum();
      });
    },
    fetchData() {
      let data = {
        shopId: this.data.shopId,
      };
      this.setGlobalTabNum();
      getMenus(data).then((res) => {
        if (res.code !== 0) {
          return;
        }
        let shopInfo = res.data.shopInfo;
        let dinnerList = [];
        let { orderTypes } = shopInfo;
        if (orderTypes.length > 0) {
          orderTypes.forEach((item) => {
            switch (item) {
              case 1:
                dinnerList.push({
                  value: item,
                  title: "堂食",
                  extraFree: shopInfo.teaFee,
                });
                break;
              case 2:
                dinnerList.push({
                  value: item,
                  title: "打包",
                  extraFree: shopInfo.packFee,
                });
                break;
              case 3:
                dinnerList.push({
                  value: item,
                  title: "外卖配送",
                  extraFree: shopInfo.feeDelivery || 0, //配送费
                  extraFree2: shopInfo.packFeeDelivery || 0, // 配送打包费
                });
                break;
            }
          });
        }
        this.setDinnerList(dinnerList);
        let distance = null;
        if (this.data.latitude && shopInfo.latitude) {
          distance = getDistance(
            this.data.latitude,
            this.data.longitude,
            shopInfo.latitude,
            shopInfo.longitude
          );
          shopInfo.distance = distance;
        }
        let classifyList = res.data.classifyList;
        let itemMap = res.data.itemMap;

        // 过滤无效分类
        classifyList = classifyList.filter(
          (item) => itemMap[item.id] && itemMap[item.id].length > 0
        );
        this.setData({
          distance: distance,
          shopInfo: shopInfo,
          menuTitle: res.data.menuTitle,
          classifyList: classifyList,
          currentIndex: classifyList.length > 0 ? classifyList[0].id : 0,
          itemMap: itemMap,
        });
        this.initCart(data.shopId);
        wx.nextTick(() => {
          this.parseScrollNodes();
        });
      });
    },
    parseScrollNodes() {
      // 解析滚动节点
      wx.createSelectorQuery()
        .selectAll(".classify-title")
        .boundingClientRect((rects) => {
          let nodesTop = [];
          for (let item of rects) {
            nodesTop.push(item.top - rects[0].top);
          }
          this.setData({
            nodesTop: nodesTop,
          });
        })
        .exec();
    },
    handleGoodsScroll(e) {
      let nodesTop = this.data.nodesTop;
      let top = e.detail.scrollTop;
      let { classifyList } = this.data;
      for (let e = 0; e < nodesTop.length; e++) {
        if (top <= nodesTop[e + 1] && top >= nodesTop[e]) {
          if (this.currentIndex !== classifyList[e].id)
            this.setData({
              currentIndex: classifyList[e].id,
            });
        } else if (top >= nodesTop[e] && !nodesTop[e + 1]) {
          this.setData({
            currentIndex: classifyList[e].id,
          });
        }
      }
      // console.log(top, nodesTop)
    },
    handleToChangeShop() {
      if (this.data.tableNo) return;
      if (this.data.noChange) return;
      router.push({
        name: "mall/store-list",
        params: {
          shopId: this.data.shopId,
          storeType: "catering",
        },
        events: {
          change: (shopId) => {
            if (shopId !== this.data.shopId) {
              this.setData({
                shopId,
                tableNo: "",
              });
              this.fetchData();
            }
          },
        },
      });
    },
    handlePay() {
      if (!this.data.cartList.length) return;
      if (!this.data.dinnerObj) {
        this.setData({
          commodityList: "",
        });
        this.chooseDinner();
        return;
      }
      router.push({
        name: "codeorder/order",
        params: {
          shopId: this.data.shopId,
          tableNo: this.data.tableNo,
        },
        success: (res) => {
          res.eventChannel.emit("order", {
            shopId: this.data.shopId,
            shopInfo: this.data.shopInfo,
            tableNo: this.data.tableNo,
            cartList: this.data.cartList,
            totalFee: this.data.totalFee,
            num: this.data.num,
            dinnerObj: this.data.dinnerObj,
          });
        },
      });
    },
    handOnePay(data) {
      let { detail } = data;
      if (!this.data.dinnerObj) {
        this.setData({
          commodityList: detail,
        });
        this.chooseDinner();
        return;
      }
      router.push({
        name: "codeorder/order",
        params: {
          shopId: this.data.shopId,
          tableNo: this.data.tableNo,
        },
        success: (res) => {
          res.eventChannel.emit("order", {
            shopId: this.data.shopId,
            shopInfo: this.data.shopInfo,
            tableNo: this.data.tableNo,
            cartList: detail.carList,
            totalFee: detail.totalFree,
            dinnerObj: this.data.dinnerObj,
          });
        },
      });
    },
    chooseDinner() {
      const Meal_Method = wx.getStorageSync(Private_Domain_Meal_Method);
      const method = Meal_Method ? JSON.parse(Meal_Method) : "";
      console.log("就餐方式", method);
      if (method) {
        this.setData({
          dinnerObj: method,
        });
        this.setDinner({ detail: { item: method } });
        return;
      }
      let { commodityList, deskId, dinnerList } = this.data;
      let onPay = {
        detail: commodityList,
      };
      if (dinnerList.length > 1) {
        if (deskId) {
          if (dinnerList.findIndex((item) => item.value == 1) != -1) {
            this.setData({
              dinnerObj:
                this.data.dinnerList[
                  dinnerList.findIndex((item) => item.value == 1)
                ],
            });
            commodityList ? this.handOnePay(onPay) : this.handlePay();
          } else {
            this.selectComponent("#choose-dinner").open();
            return;
          }
        } else {
          this.selectComponent("#choose-dinner").open();
          return;
        }
      } else {
        this.setData({
          dinnerObj: this.data.dinnerList[0],
        });
        commodityList ? this.handOnePay(onPay) : this.handlePay();
      }
    },
    setDinner(data) {
      let { item } = data.detail;
      let { commodityList } = this.data;
      let onPay = {
        detail: commodityList,
      };
      this.setData({
        dinnerObj: item,
      });
      console.log("选择的就餐方式", item);
      wx.setStorageSync(Private_Domain_Meal_Method, JSON.stringify(item));
      commodityList ? this.handOnePay(onPay) : this.handlePay();
    },

    handleCategory(e) {
      let classifyId = e.currentTarget.dataset.id;
      this.setData({
        contentId: "classify-" + classifyId,
        currentIndex: classifyId,
      });
    },
    setConetHeight() {
      //创建节点选择器
      var query = wx.createSelectorQuery();
      //选择id
      var that = this;
      query
        .selectAll(".index-address,.index-content,")
        .boundingClientRect(function (rect) {
          that.setData({
            contentHeight: rect[0].height - rect[1].height,
          });
        })
        .exec();
    },
    // setDinner(e) {
    //   let {
    //     type
    //   } = e.currentTarget.dataset
    //   this.setData({
    //     dinnerType: type,
    //     showDinner: false,
    //   })
    //   this.setDinnerType(type)
    //   getApp().globalData.dinnerType = type
    //   getApp().globalData.dinnerShopid = this.data.shopId
    // },
    setGlobalTabNum() {
      let { deskId, shopId } = this.data;
      if (deskId) {
        queryTables({
          id: deskId,
          shopId,
        }).then((res) => {
          if (res.code == 0) {
            this.setData({
              tableNo: res.data.tableNo,
            });
            getApp().globalData.dinnerShopid = this.data.shopId;
            getApp().globalData.dinnerTabNum = res.data.tableNo;
          }
        });
      }
    },
    getCoupon() {
      getCoupon({})
        .then((res) => {
          let { data } = res;
          let filter = JSON.parse(
            JSON.stringify(
              data.filter(
                (item) => item.couponType !== "exchange" && item.status == 2
              )
            )
          ).slice(0, 2);
          filter.length === 0 &&
            this.setData({
              isShowCouponDown: false,
            });
          filter.forEach((item) => {
            item.pullDown = false;
          });
          this.setData({
            couponList: filter,
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    pullDownCoupon({ target }) {
      const { receivecode, index } = target.dataset;
      let { couponList } = this.data;
      if (couponList[index].pullDown) return;
      pullDownCoupon({
        receiveCode: receivecode,
      }).then((res) => {
        if (res.code == 0) {
          couponList[index].pullDown = true;
          this.setData({
            couponList,
          });
          wx.showToast({
            title: "领取成功",
          });
        }
      });
    },
    toCouponCenter() {
      router.push({
        name: "member/couponCenter",
      });
    },
  },
});
